package com.example.demo.task;

//import com.example.demo.redis.RedisUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.LotteryRedisData;
import com.example.demo.redis.RedisUtils;
import com.example.demo.util.MD5Util;
import com.example.demo.util.Md5UtilTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @Classname ScheduleTasks
 * @Description TODO
 * @Date 2019/10/29 10:43
 * @Created by yby
 */
@Component
//@DisallowConcurrentExecution
public class ScheduleTasks {

    private static Logger logger = LoggerFactory.getLogger(ScheduleTasks.class);

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ScheduleTest scheduleTest;

    //@Scheduled(cron="0/6 * * * * ? ")  //每60秒执行一次
    public void scanScheduleData() {
        System.out.println("每60秒执行一次....");
        //扫描缓存信息
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        executorService.execute(new ScheduleTasks.lotteryCacheThread());

    }

    /**
     * 扫描机器缓存线程
     */
    private class lotteryCacheThread implements Runnable {
        @Override
        public void run() {
            System.out.println("我是run方法执行=======================");
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread());
            }
        }
    }

    //@Scheduled(cron="0 */1 * * * ?")  //每1秒执行一次0 */1 * * *
    public void testCron1() {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info(sdf.format(new Date()) + "*********每1秒执行一次");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            redisUtils.set("LOTTERY_" + i, "{\"cpodd\"：\"888\",\"status\":\"online\"} ");
        }
        Set<String> keys = stringRedisTemplate.keys("LOTTERY_*");
        for (String key : keys) {
            String str = stringRedisTemplate.opsForValue().get(key);
            JSONObject jsonObject = JSONObject.parseObject("str");
            String cpOdd = (String) jsonObject.get("cpOdd");
            String status = (String) jsonObject.get("status");
            long lastUpdateTime = (long) jsonObject.get("lastUpdateTime");
            long currentTime = System.currentTimeMillis();
            if (!"online".equals(status)) { //卡纸啊什么的
                //更新数据库

            }
        }
        List<String> strings = stringRedisTemplate.opsForValue().multiGet(keys);//获取所有的value
        //logger.info("myObjectList:{}",strings.toString());
        long end = System.currentTimeMillis();
        logger.info(end - start + "*********遍历完毕");

        /*stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
                for (int i=0;i<keys.size();i++) {
                    connection.set(keys.get(i).getBytes(),value.getBytes());
                }
                return null;
            }
        });*/


    }


    /**
     * Redis 批量数据set get操作
     */
    //@PostConstruct
    public void batchRedisData() {
        /**
         //scheduleTest.speak();
         /*if(1==1){
         System.out.println("初始化失败！！！");
         return;
         }*/
       /* List<LotteryRedisData> dataList =new ArrayList<>();
        List<String> keys =new ArrayList<>();
        LotteryRedisData LotteryRedisData=new LotteryRedisData();
        LotteryRedisData.setCpOdd("aaaaaa");
        LotteryRedisData.setStatus("ONLINE");
        dataList.add(LotteryRedisData);
        LotteryRedisData LotteryRedisData1=new LotteryRedisData();
        LotteryRedisData1.setCpOdd("bbbbbb");
        LotteryRedisData1.setStatus("ONLINE");
        dataList.add(LotteryRedisData1);
        //批量set数据
        stringRedisTemplate.executePipelined(new RedisCallback<List<Object>>() {
            @Override
            public List<Object> doInRedis(RedisConnection redisConnection) throws DataAccessException {

                for (LotteryRedisData lotteryRedisData : dataList) {
                    lotteryRedisData.setLastUpdateTime(System.currentTimeMillis());
                    redisConnection.set(("CACHE:LOTTERY:"+  MD5Util.getMD5Encode(lotteryRedisData.getCpOdd())).getBytes(),JSONObject.toJSONString(lotteryRedisData).getBytes());
                }
                return null;
            }
        });

        String key1= "CACHE:LOTTERY:"+MD5Util.getMD5Encode("aaaaaa");
        String key2= "CACHE:LOTTERY:"+MD5Util.getMD5Encode("bbbbbb");
        keys.add(key1);
        keys.add(key2);
        //批量get数据
        List<Object> objects = stringRedisTemplate.executePipelined(new RedisCallback<List<Object>>() {
            @Override
            public List<Object> doInRedis(RedisConnection redisConnection) throws DataAccessException {
                for (String key : keys) {
                    redisConnection.get(key.getBytes());
                }
                return null;
            }
        });
        *//*for (Object object : objects) {
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            System.out.println("jsonObject="+jsonObject);
        }*//*
        JSONArray jsonArray = JSONArray.parseArray(objects.toString());
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println("jsonObject11 ===="+jsonObject.toString());
            long currentTime = System.currentTimeMillis();
            Long lastUpdateTime = (Long)jsonObject.get("lastUpdateTime");
            System.out.println("lastUpdateTime="+lastUpdateTime);
        }
        System.out.println("objects="+objects.toString());*/

    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str1 = "2019-10-31 16:00:00";
        String str2 = "2019-10-31 16:05:00";
        long ts1 = simpleDateFormat.parse(str1).getTime();
        long ts2 = simpleDateFormat.parse(str2).getTime();
        System.out.println(ts1);
        System.out.println(ts2);
        System.out.println((ts2 - ts1));
        /*LotteryRedisData LotteryRedisData=new LotteryRedisData();
        LotteryRedisData.setCpOdd("10000");
        LotteryRedisData.setStatus("online");
        LotteryRedisData.setLastUpdateTime(120325466l);
        String s = JSONObject.toJSONString(LotteryRedisData);
        System.out.println("s="+s);*/

        /*org.json.JSONObject json1 = new org.json.JSONObject();
        org.json.JSONObject json2 = new org.json.JSONObject();
        JSONArray jsonArray = new JSONArray();
        json1.put("cpOdd", "100001");
        json1.put("orderId", "1");
        jsonArray.put(json1);
        json2.put("result", jsonArray);
        json2.put("time",String.valueOf(System.currentTimeMillis()));
        JSONObject jsonObject=new JSONObject();
        JSONObject jsonObject2=new JSONObject();
        com.alibaba.fastjson.JSONArray jsonArray1=new com.alibaba.fastjson.JSONArray();
        jsonObject.put("cpOdd", "100001");
        jsonObject.put("orderId", "1");
        jsonArray1.add(jsonObject);
        jsonObject2.put("result", jsonArray1);
        jsonObject2.put("time",String.valueOf(System.currentTimeMillis()));
        System.out.println("json="+json2.toString());
        System.out.println("jsonObject="+jsonObject2.toString());*/

        System.out.println(getStatusType("paper"));

    }

    public static Integer getStatusType(String status) {
        int type = 1; //默认1
        switch (status) {
            case "online":
                type = 1;
                break;
            case "offline":
                type = -1;
                break;
            case "paper":
                type = 0;
                break;
        }
        return type;
    }
}
